/*
 * @Description: 
 * @Author: zhangwei
 * @Date: 2023-01-31 14:27:25
 * @LastEditTime: 2023-02-08 11:24:41
 * @LastEditors: zhangwei
 */
import axios from "axios";
import type {
  AxiosInstance,
  AxiosRequestConfig,
  AxiosRequestHeaders,
  AxiosError,
} from "axios";

import qs from "qs";
import { config } from "@/config/axios/config";
const { result_code, base_url, request_timeout, default_headers } = config;


// 创建axios实例
const service: AxiosInstance = axios.create({
  baseURL: base_url, // api 的 base_url
  timeout: request_timeout, // 请求超时时间
  withCredentials: false // 禁用 Cookie 等信息
})

// request拦截器
service.interceptors.request.use(
  config => {
    const params = config.params || {}
    const data = config.data || false
    if (
      config.method?.toUpperCase() === 'POST' &&
      (config.headers as AxiosRequestHeaders)['Content-Type'] ===
        'application/x-www-form-urlencoded'
    ) {
      config.data = qs.stringify(data)
    }
    // get参数编码
    if (config.method?.toUpperCase() === 'GET' && params) {
      let url = config.url + '?'
      for (const propName of Object.keys(params)) {
        const value = params[propName]
        if (value !== void 0 && value !== null && typeof value !== 'undefined') {
          if (typeof value === 'object') {
            for (const val of Object.keys(value)) {
              const params = propName + '[' + val + ']'
              const subPart = encodeURIComponent(params) + '='
              url += subPart + encodeURIComponent(value[val]) + '&'
            }
          } else {
            url += `${propName}=${encodeURIComponent(value)}&`
          }
        }
      }
      // 给 get 请求加上时间戳参数，避免从缓存中拿数据
      // const now = new Date().getTime()
      // params = params.substring(0, url.length - 1) + `?_t=${now}`
      url = url.slice(0, -1)
      config.params = {}
      config.url = url
    }
    return config
  },
  (error: AxiosError) => {
    // Do something with request error
    Promise.reject(error.message)
  }
)

// response 拦截器
service.interceptors.response.use(
  async (response) => {
    const { data } = response;
    const config = response.config;
    if (!data) {
      // 返回“[HTTP]请求没有返回值”;
      return Promise.reject("返回数据结构错误，no data");
    }
    // 二进制数据则直接返回
    if (
      response.request.responseType === "blob" ||
      response.request.responseType === "arraybuffer"
    ) {
      return response.data;
    }

    // 校验状态码，错误返回错误实体
    const code = data.code || result_code;
    if (code != result_code) {
      return Promise.reject(data);
    }
    
    // 获取错误信息
    return Promise.resolve(data);;
  },
  (error: AxiosError) => {
    console.log(error.message.toString());
    return Promise.reject(error.message.toString())
  }
)

export { service };